package com.tyj.tuyijieapp.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.tyj.tuyijiecommon.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p></p>
 *
 * @author lhf
 * @since 2020/6/6
 */
@Component
public class FailureHandler implements AuthenticationFailureHandler {
    private static Logger log = LoggerFactory.getLogger(FailureHandler.class);
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error(exception.getMessage());
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSONObject.toJSONString(Result.builder().code(Result.ResultCode.LOGIN_FAILURE.getCode()).mes(Result.ResultCode.LOGIN_FAILURE.getMes()).build()));
        writer.flush();
        writer.close();
    }
}
